package com.gitee.minimalismstyle.fresh.common.dubbo.filter

import com.alibaba.dubbo.common.Constants
import com.alibaba.dubbo.rpc.Filter
import com.alibaba.dubbo.rpc.Invocation
import com.alibaba.dubbo.rpc.Invoker
import com.alibaba.dubbo.rpc.Result
import com.fasterxml.jackson.databind.ObjectMapper
import com.gitee.minimalismstyle.fresh.common.core.const.CacheConst
import com.gitee.minimalismstyle.fresh.common.core.domain.Context
import com.gitee.minimalismstyle.fresh.common.security.domain.FreshUserDetails
import org.apache.dubbo.common.extension.Activate
import org.apache.dubbo.rpc.RpcContext

/**
 * 提供者过滤器
 * @author maoxiaodong
 */
@Activate(group = [Constants.PROVIDER])
class ProviderContextFilter : Filter {

    override fun invoke(invoker: Invoker<*>, invocation: Invocation): Result {
        var userString = RpcContext.getContext().getAttachment(CacheConst.USER_INFO_KEY)
        if(userString != null){
            val om = ObjectMapper()
            var user: FreshUserDetails = om.readValue(userString, FreshUserDetails::class.java)
            // 将当前用户信息存到应用上下文
            Context.set(CacheConst.USER_INFO_KEY, user)
        }
        return invoker.invoke(invocation)
    }

}